<?php
/**
 * Created by PhpStorm.
 * User: jungshen
 * Date: 2019/3/1
 * Time: 14:30
 */

namespace app\api2\controller\member;


use app\api\controller\BasicUserApi;
use app\api2\Service\DemandService;
use service\DataService;
use service\LogService;
use service\ToolsService;
use service\WechatService;
use think\Db;
use think\Exception;
use think\facade\Validate;

/**
 * 询价控制器
 * Class Inquiry
 * @package app\api2\controller\member
 */
class Demand extends BasicUserApi
{
    /**
     * 发布需求
     * @return \think\response\Json
     */
    function release(){
        if($this->request->isPost()) {
            $post = $this->request->only(['title', 'mobile'] , 'post');
            if(!isset($post['title'])||!isset($post['mobile'])){
                return json(['msg'=>'标题和电话不能为空'],500);
            }
            $post['mid']=UID;
            $post['status']=0;
            $post['noticed']=0;
            $post['addtime']=time();
            $post['order_sn']=DataService::createSequence(10,'DEMAND');
            Db::name('member_demand')->insert($post);
            return json(['msg'=>'发布成功,请等待审核'],200);
        }
    }

    /**
     * 正在抢单的列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    function lists(){
        $page_size=$this->request->get('page_size',10);
        $page_now=$this->request->get('page_now',1);
        //查询我抢了单的
        $demand_offer=Db::name('demand_offer')
            ->where('mid',UID)
            ->column('demand_id');

        $db=Db::name('member_demand')
            ->where('mid','<>',UID)
            /*->where('endtime','>',time())*/
            ->where('status','<>',0);
            //->where('status',1);
        if($demand_offer){
            $db->where('id','not in',$demand_offer);
        }
        $list=$db->field('id,title,address,lat,lng,FROM_UNIXTIME(endtime,\'%Y-%m-%d %H:%i\') endtime,FROM_UNIXTIME(addtime,\'%Y-%m-%d\') addtime,status')
            ->page($page_now,$page_size)
            ->order('status desc,endtime desc,id desc')
            ->select();
        foreach ($list as &$v){
            if($v['endtime']<date('Y-m-d H:i')){
                $v['status']=-1;
            }
        }
        return json(['msg'=>'success','data'=>$list],200);
    }

    /**
     * 需求详情
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    function view(){
        $id=$this->request->get('id');
        //查询需求详情
        $demand=Db::name('member_demand')
            ->where('id',$id)
            ->hidden('type,extend_type,noticed')
            ->find();
        if($demand){
            $demand['addtime']=date('Y-m-d',$demand['addtime']);
            $demand['endtime']=date('Y-m-d H:i',$demand['endtime']);
            $demand['images']=explode('|',$demand['images']);
            $demand_offer=Db::name('demand_offer')
                ->where('demand_id',$id)
                ->where('mid',UID)
                ->where('status',2)
                ->count();
            if($demand_offer<1){
                //TODO::后期控制电话显示
                //unset($demand['mobile']);
            }
        }
        return json(['msg'=>'success','data'=>$demand],200);
    }

    /**
     * 竞标
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    function bid(){
        $id=$this->request->get('id');
        //不能给自己发布的报价 不能重复报价
        $demand=Db::name('member_demand')
            ->where('id',$id)
            ->field('mid,price,extend_type,endtime,min_credit,status')
            ->find();

        if($demand['endtime']<=time()||$demand['status']!=1){
            return json(['msg'=>'该需求已结束'],500);
        }
        if(UID==$demand['mid']){
            return json(['msg'=>'您不能参与自己的需求'],500);
        }
        $member=Db::name('store_member')
            ->where('id',UID)
            ->field('money,type,id,credit')
            ->find();
        if($member['credit']<$demand['min_credit']){
            return json(['msg'=>'您的信用分太低,不能参与'],500);
        }
        if($member['type']==0){
            return json(['msg'=>'请先入驻'],500);
        }else{
            //判断是否过期
            if($member['type']==1){
                $attach_info=Db::name('worker_info')
                    ->where('mid',UID)
                    ->field('expiry_time,work_type_ids type_ids')->find();
            }else{
                $attach_info=Db::name('supplier_info')
                    ->where('mid',UID)
                    ->field('expiry_time,supplier_type_ids type_ids')->find();
            }
            if($attach_info['expiry_time']<time()){
                return json(['msg'=>'您的会员已过期,请先续费'],500);
            }
			if(!in_array($demand['extend_type'],explode(',',$attach_info['type_ids']))){
              return json(['msg'=>'您的技能与该需求不匹配'],500);
            }
            //判断是否是超级会员
            /*$isSuper=MemberService::isSuper($member);
            if($isSuper) {
                $real_money=0;
            }else{
                //VIP
                $real_money=$demand['price'];
            }*/
            //判断余额
            $real_money=$demand['price'];
            if($member['money']<$real_money){
                //VIP
                return json(['msg'=>'您的团币不足'],500);
            }

        }

        //查询是否报价了
        $demand_offer=Db::name('demand_offer')
            ->where('mid',UID)
            ->where('demand_id',$id)
            ->find();
        if($demand_offer){
            return json(['msg'=>'您已参与过该需求了'],500);
        }
        //新增信息
        $io_data['mid']=UID;
        $io_data['demand_id']=$id;
        $io_data['addtime']=time();
        $io_data['status']=1;
        $io_data['offer_money']=$real_money;//抢单费用
        $io_data['order_sn']=DataService::createSequence(10,'DEMANDOFFER');
        Db::name('demand_offer')->insert($io_data);
        //扣除广告币
        if($real_money>0){
            log_account_change(UID,-$real_money,0,'参与需求扣除余额',4);
        }
        return json(['msg'=>'参与成功,正在候选'],200);
    }
    /**
     * 我参与的
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    function my_participation(){
        $page_size=$this->request->get('page_size',10);
        $page_now=$this->request->get('page_now',1);
        $db=Db::name('demand_offer')
            ->alias('o')
            ->join('member_demand d','o.demand_id=d.id')
            ->where('o.mid',UID);
        $list=$db->field('d.id,d.title,d.address,d.lat,d.lng,FROM_UNIXTIME(d.endtime,\'%Y-%m-%d %H:%i\') endtime,
        FROM_UNIXTIME(d.addtime,\'%Y-%m-%d\') addtime,o.status')
            ->page($page_now,$page_size)
            ->order('o.id desc')
            ->select();
        return json(['msg'=>'success','data'=>$list],200);
    }

    /**
     * 我发布的
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    function mine(){
        $page_size=$this->request->get('page_size',10);
        $page_now=$this->request->get('page_now',1);
        //查询我抢了单的
        $db=Db::name('member_demand')
            ->where('mid',UID);
        $list=$db->field('id,title,address,lat,lng,FROM_UNIXTIME(endtime,\'%Y-%m-%d %H:%i\') endtime,FROM_UNIXTIME(addtime,\'%Y-%m-%d\') addtime,status')
            ->page($page_now,$page_size)
            ->order('status desc,id desc')
            ->select();
        return json(['msg'=>'success','data'=>$list],200);
    }

    /**
     * 关闭需求
     * @return \think\response\Json
     */
    function close(){
        $id=$this->request->get('id');
        Db::name('member_demand')
            ->where('id',$id)
            ->where('mid',UID)
            ->setField('status',-1);
        //退保证金
        DemandService::back_money($id,true);
        return json(['msg'=>'关闭成功'],200);
    }

    /**
     * 需求继续
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    function open(){
        $id=$this->request->get('id');
        $demand=Db::name('member_demand')
            ->where('id',$id)
            ->where('mid',UID)
            ->hidden('id,status,addtime,noticed,order_sn,is_back_money')
            ->find();
        //复制一份新需求
        $demand['addtime']=time();
        $demand['order_sn']=DataService::createSequence(10,'DEMAND');
        $demand['noticed']=0;
        $demand['status']=0;
        Db::name('member_demand')->insert($demand);
        return json(['msg'=>'开启成功,请等待审核'],200);
    }

    /**
     * 删除需求
     * @return \think\response\Json
     */
    function del(){
        $id=$this->request->get('id');
        Db::transaction(function ()use($id){
            Db::name('member_demand')
                ->where('id',$id)
                ->where('mid',UID)
                ->delete();
            DemandService::back_money($id,true);
            Db::name('demand_offer')
                ->where('demand_id',$id)
                ->delete();
        });
        return json(['msg'=>'删除成功'],200);
    }

    /**
     * 查看|编辑我的发布
     * @return \think\response\Json
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    function edit(){
        if($this->request->isPost()){
            $post=$this->request->only(['address','lat','lng','price','id'],'post');
            $validate = Validate::make([
                'address|详细地址'  => 'require',
                'lat'  => 'require',
                'lng'  => 'require',
                'id|ID'  => 'require',
                'price|参与保证金' => 'require|egt:0'
            ]);
            if(false===$validate->check($post)){
                return json(['msg'=>$validate->getError()],500);
            }
            Db::name('member_demand')
                ->where('mid',UID)
                ->where('id',$post['id'])
                ->update($post);
            return json(['msg'=>'修改成功']);
        }else{
            $id=$this->request->get('id');
            $lat=$this->request->get('lat','29.34588019989763200');
            $lng=$this->request->get('lng','106.65887899864005000');
            //查询需求详情
            $demand=Db::name('member_demand')
                ->where('id',$id)
                ->where('mid',UID)
                ->hidden('noticed')
                ->find();
            if($demand){
                $demand['addtime']=date('Y-m-d',$demand['addtime']);
                $demand['endtime']=date('Y-m-d H:i',$demand['endtime']);
                $demand['images']=explode('|',$demand['images']);
                /**
                 * 抢单列表
                 */
                $demand_offer=Db::name('demand_offer')
                    ->alias('o')
                    ->join('store_member m','m.id=o.mid')
                    ->where('o.demand_id',$id)
                    ->order('m.sort,tmp,juli,credit desc')
                    ->field('o.id,o.status,o.mid,m.headimg,m.type,m.address,m.lng,m.credit,m.lat,if(isnull(lat),1,0) tmp,
                (2 * 6378.137* ASIN(SQRT(POW(SIN(3.1415926535898*('.$lat.'-m.lat)/360),2)+COS(3.1415926535898*'.$lat.'/180)* COS(m.lat * 3.1415926535898/180)*POW(SIN(3.1415926535898*('.$lng.'-m.lng)/360),2))))*1000 as juli')
                    ->select();
                foreach ($demand_offer as &$v){
                    if($v['type']==1){
                        $v['attach_info']=Db::name('worker_info')
                            ->where('mid',$v['mid'])
                            ->field('name,work_type_ids tags')
                            ->find();
                    }elseif($v['type']==2){
                        $v['attach_info']=Db::name('supplier_info')
                            ->where('mid',$v['mid'])
                            ->field('name,supplier_type_ids tags')
                            ->find();
                    }
                    $v['attach_info']['tags']=explode(',',$v['attach_info']['tags']);
                    foreach ($v['attach_info']['tags'] as &$tag){
                        $tag=getmodel($tag,'my_cate','title');
                    }
                    $v['attach_info']['tags']=implode(' ',$v['attach_info']['tags']);
                }
                $demand['offer_list']=$demand_offer;
                $demand['offer_count']=count($demand_offer);
                /**
                 * 系统推荐
                 */
                if($demand['type']==32){
                    //厂家
                    $recommend=Db::name('supplier_info')
                        ->alias('si')
                        ->join('store_member m','m.id=si.mid')
                        ->leftJoin('earnest e','e.mid=m.id and e.status=1')
                        ->whereRaw('FIND_IN_SET('.$demand['extend_type'].',si.supplier_type_ids)')
                        ->where('si.expiry_time','>',time())
                        ->where('m.status',1)
                        ->order('e.money,m.credit desc,si.grade_id desc,m.real_address desc,m.browse desc')
                        ->field('m.headimg,si.name,m.credit,m.lat,m.lng,si.id,si.mid')
                        ->limit(10)
                        ->select();
                }else{
                    //工人
                    $recommend=Db::name('worker_info')
                        ->alias('si')
                        ->join('store_member m','m.id=si.mid')
                        ->leftJoin('earnest e','e.mid=m.id and e.status=1')
                        ->whereRaw('FIND_IN_SET('.$demand['extend_type'].',si.work_type_ids)')
                        ->where('si.expiry_time','>',time())
                        ->where('m.status',1)
                        ->order('e.money,m.credit desc,si.grade_id desc,m.real_address desc,m.browse desc')
                        ->field('m.headimg,si.name,m.credit,m.lat,m.lng,si.id,si.mid')
                        ->limit(10)
                        ->select();
                }
                $demand['recommend']=$recommend;
            }
            return json(['msg'=>'success','data'=>$demand],200);
        }
    }

    /**
     * 选择服务商
     * @return \think\response\Json
     * @throws \WeChat\Exceptions\InvalidResponseException
     * @throws \WeChat\Exceptions\LocalCacheException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    function choose_offer(){
        $demand_id=$this->request->get('demand_id');
        $demand=Db::name('member_demand')
            ->where('id',$demand_id)
            ->where('mid',UID)
            ->where('status',1)
            ->field('title,mobile')
            ->find();
        if(!$demand){
            return json(['msg'=>'需求异常'],500);
        }
        $offer_id=$this->request->get('offer_id');
        $res=Db::name('demand_offer')
            ->where('id',$offer_id)
            ->where('demand_id',$demand_id)
            ->where('status',1)
            ->setField('status',2);
        if($res){
            //推送模板消息
            $offer_mid=Db::name('demand_offer')
                ->where('id',$offer_id)
                ->value('mid');
            $offer_member=Db::name('store_member')
                ->where('id',$offer_mid)
                ->field('id,openid')
                ->find();
            $redis=ToolsService::get_redis();
            $param['touser']=$offer_member['openid'];
            $param['template_id']='9YjljzCrcgpYSPi5cfq1-dz_a8H6AxlWuwZWydCKoQw';
            $param['page']='pages/nf_my_qd_demand_list/nf_my_qd_demand_list';
            $param['form_id']=$redis->rPop('jujin_wemini_form_id_list_'.$offer_member['id']);
            $param['data']=[
                'keyword1'=>[
                    'value'=>$demand['title']
                ],
                'keyword2'=>[
                    'value'=>$demand['mobile']
                ]
            ];
            if(!$param['form_id']){
                LogService::write('模板消息',$offer_member['id'].':FormId不足，微信推送失败');
            }else{
                try{
                    $tmp=WechatService::WeMiniTemplate()->send($param);
                }catch (\Exception $e){
                    LogService::write('模板消息',$e->getMessage());
                }
            }
        }else{
            return json(['msg'=>'该订单已过期'],500);
        }
        return json(['msg'=>'入围成功']);
    }
}